package com.nbjtjc.safe.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @auther guqianbin
 * @date 2018/4/14 13:07
 **/
public class ExcelUtil {


    /**
     * 根据数据生成excel
     *
     * @param columnNames 列名字
     * @param columnsData 列对应的数据
     * @return
     */
    public static File getExcelFile(List<String> columnNames, List<List<String>> columnsData
            , int length,String filePath) throws IOException {
        int columnCount=columnNames.size();
        int rowCount=length;
        File excelFile = new File(filePath);
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("sheet1");
        OutputStream outputStream = new FileOutputStream(filePath);
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
        //初始化row
        for (int i = 0; i < length; i++) {
            Row row = sheet.createRow(i);
        }
        //初始化表头
        Row row = sheet.getRow(0);
        for (int i = 0; i < columnCount; i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(columnNames.get(i));
        }
        for(int i=1;i<=rowCount;i++){
            Row row1=sheet.createRow(i);
            for(int j=0;j<columnCount;j++){
                Cell cell=row1.createCell(j);
                cell.setCellValue(columnsData.get(j).get(i-1));
            }
        }
        //创建文件流
        OutputStream stream = new FileOutputStream(filePath);
        //写入数据
        workbook.write(stream);
        //关闭文件流
        stream.close();
        return excelFile;
    }
}
